package com.scrcu.cloud.wechat.home.endpoint.staff.service.Iml;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scrcu.cloud.wechat.home.endpoint.common.model.RestResponse;
import com.scrcu.cloud.wechat.home.endpoint.common.utils.HttpUtils;
import com.scrcu.cloud.wechat.home.endpoint.common.utils.SnowWorkId;
import com.scrcu.cloud.wechat.home.endpoint.customer.entity.AppInfo;
import com.scrcu.cloud.wechat.home.endpoint.customer.entity.BookInfo;
import com.scrcu.cloud.wechat.home.endpoint.customer.entity.Institution;
import com.scrcu.cloud.wechat.home.endpoint.customer.mapper.AppInfoMapper;
import com.scrcu.cloud.wechat.home.endpoint.customer.mapper.BookMapper;
import com.scrcu.cloud.wechat.home.endpoint.customer.mapper.InstMapper;
import com.scrcu.cloud.wechat.home.endpoint.staff.constant.Constants;
import com.scrcu.cloud.wechat.home.endpoint.staff.dto.AssessDto;
import com.scrcu.cloud.wechat.home.endpoint.staff.entity.*;
import com.scrcu.cloud.wechat.home.endpoint.staff.mapper.*;
import com.scrcu.cloud.wechat.home.endpoint.staff.service.IStaffService;
import com.scrcu.cloud.wechat.home.endpoint.staff.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.select.Top;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.PropertyTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Array;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class StaffServiceIml extends ServiceImpl<StaffInfoMapper, StaffInfo> implements IStaffService {

    @Autowired
    private AppInfoMapper appInfoMapper;

    @Autowired
    private BookMapper bookMapper;

    //企业微信访问url
    @Value("${enterprise.wechat.gettokenUrl}")
    private String getTokenUrl;
    @Value("${enterprise.wechat.corpid}")
    private String corpid;
    @Value("${enterprise.wechat.corpsecret}")
    private String corpsecret;

    @Value("${default.tencent.appid2}")
    private String appId;
    @Value("${tencent.access.token.url}")
    private String accessTokenUrl;
    @Value("${tencent.access.token.grantType}")
    private String grantType;

    //企业微信访问url
    @Value("${enterprise.wechat.departmentListUrl}")
    private String departmentListUrl;

    @Autowired
    private GroupMapper groupMapper;
    @Autowired
    private CmtMemberMapper cmtMemberMapper;
    @Autowired
    private TopicMapper topicMapper;
    @Autowired
    private AssessMapper assessMapper;
    @Autowired
    private StaffInfoMapper staffInfoMapper;
    @Autowired
    private GroupSubRecordMapper groupSubRecordMapper;
    @Autowired
    private InstMapper instMapper;

    @Override
    public RestResponse getSecret(String appid) {
        String secret = appInfoMapper.getSecret(appid);
        HashMap<String,Object> res = new HashMap<>();
        res.put("secret",secret);
        return RestResponse.success(res);
    }

    @Override
    public RestResponse getaccessToken(String appid) {
        Map<String,String> res = new HashMap<>();
        String secret = null;
        try{
            if (appid==null||appid.equalsIgnoreCase("null")||appid.length()==0){
                appid = appId;
                secret = appInfoMapper.getSecret(appid);
            }else{
                secret = appInfoMapper.getSecret(appid);
            }
        }catch(Exception e){
            e.printStackTrace();
            log.error("取得的secret出错");
            return RestResponse.failed("取得的secret出错, appid> "+appid);
        }

        String returnJson = null;

        returnJson = HttpUtils.builder()
                .url(accessTokenUrl)
                .addParam("appid", appId)
                .addParam("secret", secret)
                .addParam("grant_type", grantType)
                .get()
                .execute();

        String access_token =String.valueOf(com.alibaba.fastjson.JSONObject.parseObject(returnJson).get("access_token"));
        log.info("accessToken：{}", access_token);
        res.put("accessToken",access_token);
        return RestResponse.success(res);
    }


    @Override
    public RestResponse getaccessTokenqiye(String appid) {
        HashMap<String,Object> res = new HashMap<>();
        QueryWrapper<AppInfo> qw = new QueryWrapper<>();
        qw.eq("app_id", appid);
        AppInfo appInfo = appInfoMapper.selectOne(qw);
        if (appInfo==null){
            log.warn("appid错误");
            return RestResponse.failed("无权获取token");
        }
        String returnJson = null;
        try{
            returnJson = HttpUtils.builder()
                    .url(getTokenUrl)
                    .addParam("corpid", corpid)
                    .addParam("corpsecret", corpsecret)
                    .get()
                    .execute();
        }catch (Exception e){
            log.error("请求access token出错");
            e.printStackTrace();
        }
        log.info("returnJson>"+returnJson);
//        String data =String.valueOf(JSONObject.parseObject(returnJson).get("data"));
        String access_token =String.valueOf(JSONObject.parseObject(returnJson).get("access_token"));
//        if (access_token==null|| access_token.equalsIgnoreCase("null")){
//            log.error("openid错误");
//            return RestResponse.failed("openid错误");
//        }
        res.put("access_token",access_token);
        return RestResponse.success(res);
    }

    @Override
    public RestResponse getInstList(String accessToken, String id) {
        HashMap<String,Object> res = new HashMap<>();
        String returnJson = null;
        try{
            returnJson = HttpUtils.builder()
                    .url(departmentListUrl)
                    .addParam("access_token", accessToken)
                    .addParam("id", id)
                    .get()
                    .execute();
        }catch (Exception e){
            log.error("请求access token出错");
            e.printStackTrace();
        }
        log.info("returnJson>"+returnJson);
        String department =String.valueOf(JSONObject.parseObject(returnJson).get("department"));
        res.put("department",department);
        return RestResponse.success(res);
    }

    @Override
    public RestResponse processBook(String bookid, String staffid) {

        StaffInfo staffInfo = getBaseMapper().selectById(staffid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息，请核对");

        BookInfo bookInfo = bookMapper.selectById(bookid);
        if (bookInfo==null){
            return RestResponse.failed("没有找到该预约记录");
        }

//        0 为未完成  1 为完成  2为逾期 3为已取消

        if (bookInfo.getStatus()==0){
            bookInfo.setStatus(99);
            LocalDateTime createDate = LocalDateTime.now();
            bookInfo.setStaffId(staffInfo.getStaffId());
            bookInfo.setStaffName(staffInfo.getName());
            bookInfo.setDoneTime(createDate);
            bookMapper.updateById(bookInfo);
            return RestResponse.success("核销成功");
        }else if (bookInfo.getStatus()==1){
            return RestResponse.failed("该预约已经被核销了");
        }else if (bookInfo.getStatus()==2){
            return RestResponse.failed("该预约已逾期");
        }else if (bookInfo.getStatus()==3){
            return RestResponse.failed("该预约已取消");
        }

        return RestResponse.failed("未知错误");
    }

    @Override
    public RestResponse submitStaff(String openid, String oanum, String name, String mapId,String city, String area) {
        QueryWrapper<StaffInfo> qw = new QueryWrapper<>();
        qw.eq("staff_id",openid);
        if(getBaseMapper().selectOne(qw)!=null){
            log.info("已有该员工注册信息");
            return RestResponse.failed("已有该员工注册信息");
        }

        StaffInfo staffInfo = new StaffInfo();
        staffInfo.setStaffId(openid);
        staffInfo.setName(name);
        staffInfo.setOpenid(openid);
        staffInfo.setOanum(oanum);
        staffInfo.setMapId(mapId);
        staffInfo.setUserid(openid);
        staffInfo.setPriority(0);
        staffInfo.setCity(city);
        staffInfo.setArea(area);
        LocalDateTime createDate = LocalDateTime.now();
        staffInfo.setCreateTime(createDate);

        getBaseMapper().insert(staffInfo);

        return RestResponse.success(staffInfo);
    }

    @Override
    public RestResponse judgeStaff(String openid) {
        QueryWrapper<StaffInfo> qw = new QueryWrapper<>();
        qw.eq("staff_id",openid);
        StaffInfo staffInfo = getBaseMapper().selectOne(qw);
        if (staffInfo!=null){
            String mapid = staffInfo.getMapId();
            Institution institution = instMapper.selectById(mapid);
            StaffInfoPlus staffInfoPlus = new StaffInfoPlus();
            staffInfoPlus.setInst("");
            if (institution!=null)
                staffInfoPlus.setInst(institution.getName());
            staffInfoPlus.setStaffId(staffInfo.getStaffId());
            staffInfoPlus.setCity(staffInfo.getCity());
            staffInfoPlus.setName(staffInfo.getName());
            staffInfoPlus.setOanum(staffInfo.getOanum());
            staffInfoPlus.setOpenid(staffInfo.getOpenid());
            staffInfoPlus.setCreateTime(staffInfo.getCreateTime());
            staffInfoPlus.setIdcard(staffInfo.getIdcard());
            staffInfoPlus.setMapId(staffInfo.getMapId());
            staffInfoPlus.setPriority(staffInfo.getPriority());
            staffInfoPlus.setTelnum(staffInfo.getTelnum());
            staffInfoPlus.setOrcode(staffInfo.getOrcode());
            staffInfoPlus.setUserid(staffInfo.getUserid());
            staffInfoPlus.setPost(staffInfo.getPost());
            staffInfoPlus.setDepartment(staffInfo.getDepartment());
            staffInfoPlus.setArea(staffInfo.getArea());
            return RestResponse.success(staffInfoPlus);
        }
        return RestResponse.failed("无该员工信息");
    }

    @Override
    public RestResponse getGroupAdmin(String openid) {
        HashMap<String,Object> res = new HashMap<>();
        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息，请核对");
        if(staffInfo.getPriority()<2){
            return RestResponse.failed("无权限");
        }

        QueryWrapper<Group> qw = new QueryWrapper<>();
        ArrayList<Group> lists = (ArrayList<Group>) groupMapper.selectList(qw);
        res.put("groups",lists);
        return RestResponse.success(res);
    }

    @Override
    public RestResponse getMember(String openid, String groupid) {
        HashMap<String,Object> res = new HashMap<>();
        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息，请核对");

        //先判断获取member的人是否是被评人，只有被评人才能参与评价其他人
        QueryWrapper<CmtMember> qw = new QueryWrapper<>();
        qw.eq("oanum",staffInfo.getOanum()).eq("name",staffInfo.getName());
        if(cmtMemberMapper.selectOne(qw)==null){
            return RestResponse.failed("只有被评人才能参与评价其他人");
        }

        qw.clear();
//        QueryWrapper<CmtMember> qw = new QueryWrapper<>();
        qw.eq("group_id",groupid);
        ArrayList<CmtMember> lists = (ArrayList<CmtMember>) cmtMemberMapper.selectList(qw);
        ArrayList<MemberPlus> finalLists = new ArrayList<>();

        QueryWrapper<Group> qw2 = new QueryWrapper<>();
        qw2.eq("group_id",groupid);
        String date = groupMapper.selectOne(qw2).getStatus();

        for (CmtMember member: lists) {
            if (member.getOanum().equals(staffInfo.getOanum()))
                continue;
            MemberPlus memberPlus = new MemberPlus();
            QueryWrapper<Assess> qw3 = new QueryWrapper<>();
            qw3.eq("staff_id",openid).eq("topic_date",date)
                    .eq("member_id",member.getMemberId())
                    .eq("group_id",member.getGroupId());
            ArrayList<Assess> assess = (ArrayList<Assess>) assessMapper.selectList(qw3);
            QueryWrapper<Topic> qw4 = new QueryWrapper<>();
            qw4.eq("group_id",member.getGroupId()).eq("topic_date",date);
            int totalTopic = topicMapper.selectList(qw4).size();
            if (assess != null&&assess.size()>0){
                memberPlus.setAccessed(true);
            }else{
                memberPlus.setAccessed(false);
            }
            memberPlus.setMemberId(member.getMemberId());
            memberPlus.setInst(member.getInst());
            memberPlus.setName(member.getName());
            memberPlus.setGroupId(member.getGroupId());
            memberPlus.setPost(member.getPost());
            memberPlus.setOanum(member.getOanum());
            memberPlus.setPostType(member.getPostType());
            memberPlus.setGroupName(member.getGroupName());
            finalLists.add(memberPlus);
        }

        res.put("members",finalLists);
        return RestResponse.success(res);
    }

    @Override
    public RestResponse getTopiclist(String openid, String groupid) {
        HashMap<String,Object> res = new HashMap<>();
        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息，请核对");

        QueryWrapper<Group> qw2 = new QueryWrapper<>();
        qw2.eq("group_id",groupid);
        String date = groupMapper.selectOne(qw2).getStatus();

        QueryWrapper<Topic> qw = new QueryWrapper<>();
        qw.eq("group_id",groupid).eq("topic_date",date);
        ArrayList<Topic> lists = (ArrayList<Topic>) topicMapper.selectList(qw);
        res.put("topics",lists);

        return RestResponse.success(res);
    }

    @Override
    public RestResponse getTopiclistAdmin(String openid, String groupid, String date) {
        HashMap<String,Object> res = new HashMap<>();
        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息，请核对");

        QueryWrapper<Topic> qw = new QueryWrapper<>();
        qw.eq("group_id",groupid).eq("topic_date",date);
        ArrayList<Topic> lists = (ArrayList<Topic>) topicMapper.selectList(qw);
        res.put("topics",lists);

        return RestResponse.success(res);
    }

    @Override
    public RestResponse getTopicsWithDetail(String openid, String memberid, String groupid, String date) {
        HashMap<String,Object> res = new HashMap<>();
        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息，请核对");

        QueryWrapper<Topic> qw = new QueryWrapper<>();
        qw.eq("group_id",groupid).eq("topic_date",date);
        ArrayList<Topic> lists = (ArrayList<Topic>) topicMapper.selectList(qw);
        ArrayList<TopicPlus2> final_res = new ArrayList<>();
        for (Topic single: lists
             ) {
            TopicPlus2 topicPlus2 = new TopicPlus2();
            QueryWrapper<Assess> qw2 = new QueryWrapper<>();
            qw2.eq("member_id",Integer.parseInt(memberid))
                    .eq("group_id",Integer.parseInt(groupid))
                    .eq("topic_date",date).eq("topic_id",single.getTopicId());
            ArrayList<Assess> assesses = (ArrayList<Assess>) assessMapper.selectList(qw2);
            int good = 0;
            int ok = 0;
            int bad = 0;
            for (int i = 0; i < assesses.size(); i++) {  //描述答案   good是1 ok是2 bad是3
                if (assesses.get(i).getAnswerType()==1){
                    good+=1;
                }else if(assesses.get(i).getAnswerType()==2){
                    ok+=1;
                }else {
                    bad +=1;
                }
            }
            HashMap<String,Object> scores = new HashMap<>();
            scores.put("good",good);
            scores.put("ok",ok);
            scores.put("bad",bad);
            topicPlus2.setTopicType(single.getTopicType());
            topicPlus2.setTopicDate(single.getTopicDate());
            topicPlus2.setTopicDesc(single.getTopicDesc());
            topicPlus2.setTopicId(single.getTopicId());
            topicPlus2.setAnswerDetail(scores);
            topicPlus2.setGroupId(single.getGroupId());
            topicPlus2.setGroupName(single.getGroupName());
            topicPlus2.setCount(good+ok+bad);
            final_res.add(topicPlus2);
        }
        res.put("topics",final_res);
        return RestResponse.success(res);
    }


    @Override
    public RestResponse getGroup(String openid) {
        HashMap<String,Object> res = new HashMap<>();
        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息，请核对");

        String city = staffInfo.getCity();
        if (city.length()>=3){
            city = city.substring(0,2);
        }

        QueryWrapper<Group> qw = new QueryWrapper<>();
        qw.like("city",city);
        ArrayList<Group> lists = (ArrayList<Group>) groupMapper.selectList(qw);
        res.put("groups",lists);
        log.info("返回》"+lists);
        return RestResponse.success(res);
    }

    @Override
    public RestResponse submitForm(cn.hutool.json.JSONObject assesses) {
        log.info(assesses.toString());
        JSONArray jsarray = (JSONArray) JSONObject.parseObject(String.valueOf(assesses)).get("assesses");

        for (Object json:jsarray) {
            log.info(json.toString());
            int member_id =Integer.parseInt(String.valueOf(JSONObject.parseObject(String.valueOf(json)).get("member_id")));;
            int group_id =Integer.parseInt(String.valueOf(JSONObject.parseObject(String.valueOf(json)).get("group_id")));;
            int topic_id =Integer.parseInt(String.valueOf(JSONObject.parseObject(String.valueOf(json)).get("topic_id")));;
            String staff_id = String.valueOf(JSONObject.parseObject(String.valueOf(json)).get("staff_id"));
            String answer_type = String.valueOf(JSONObject.parseObject(String.valueOf(json)).get("answer_type"));
            StaffInfo staffInfo =  staffInfoMapper.selectById(staff_id);
            String staffName = staffInfo.getName();
            String staffOanum = staffInfo.getOanum();

            String groupName = groupMapper.selectById(group_id).getGroupName();
            String date = topicMapper.selectById(topic_id).getTopicDate();
            String desc = topicMapper.selectById(topic_id).getTopicDesc();

            QueryWrapper<Topic> qw = new QueryWrapper<>();
            qw.eq("group_id",group_id).eq("topic_date",date);
            int totalTopic = topicMapper.selectList(qw).size();
            if(jsarray.size()!=totalTopic){
                return RestResponse.failed("请提交全部题目");
            }
            Assess assess = new Assess();
            assess.setGroupId(group_id);
            assess.setAnswerType(answer_type.equals("good")? 1:(answer_type.equals("ok")? 2:3));
            assess.setGroupId(group_id);
            assess.setMemberId(member_id);
            assess.setTopicId(topic_id);
            LocalDateTime now = LocalDateTime.now();
            assess.setDoneTime(now);
            assess.setStaffId(staff_id);
            assess.setStaffName(staffName);
            assess.setStaffOanum(staffOanum);
            assess.setGroupName(groupName);
            assess.setTopicDate(date);
            assess.setTopicDesc(desc);
            assessMapper.insert(assess);
        }

        return RestResponse.success();
    }

    @Override
    public RestResponse clearAssess(String openid, String groupid,String memberid) {
        HashMap<String,Object> res = new HashMap<>();
        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息，请核对");

        QueryWrapper<Group> qw1 = new QueryWrapper<>();
        qw1.eq("group_id",groupid);
        String date = groupMapper.selectOne(qw1).getStatus();

        QueryWrapper<Assess> qw2 = new QueryWrapper<>();
        qw2.eq("group_id",groupid)
                .eq("staff_id",openid)
                .eq("topic_date",date)
                .eq("member_id",memberid);
        int deleteflag = assessMapper.delete(qw2);
        if (deleteflag>0){
            return RestResponse.success("清理成功");
        }
        return RestResponse.failed();
    }

    @Override
    public RestResponse getTopiclistDetail(String openid, String groupid, String memberid) {
        HashMap<String,Object> res = new HashMap<>();
        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息，请核对");

        QueryWrapper<Group> qw2 = new QueryWrapper<>();
        qw2.eq("group_id",groupid);
        String date = groupMapper.selectOne(qw2).getStatus();

        QueryWrapper<Topic> qw3 = new QueryWrapper<>();
        qw3.eq("group_id",groupid).eq("topic_date",date);
        ArrayList<Topic> topic_lists = (ArrayList<Topic>) topicMapper.selectList(qw3);
        ArrayList<TopicPlus> lists = new ArrayList<>();


        for (int i = 0; i < topic_lists.size(); i++) {
            TopicPlus topicPlus = new TopicPlus();
            topicPlus.setTopicId(topic_lists.get(i).getTopicId());
            topicPlus.setTopicDate(topic_lists.get(i).getTopicDate());
            topicPlus.setTopicDesc(topic_lists.get(i).getTopicDesc());
            topicPlus.setTopicType(topic_lists.get(i).getTopicType());
            topicPlus.setGroupId(topic_lists.get(i).getGroupId());
            topicPlus.setGroupName(topic_lists.get(i).getGroupName());

            QueryWrapper<Assess> qw = new QueryWrapper<>();
            qw.eq("group_id",groupid)
                    .eq("topic_date",date)
                    .eq("member_id",memberid)
                    .eq("staff_id",openid).eq("topic_id",topic_lists.get(i).getTopicId());
            Assess assess =  assessMapper.selectOne(qw);
            if(assess!=null)
                topicPlus.setAnswerType(assess.getAnswerType());
            else
                topicPlus.setAnswerType(0);
            lists.add(topicPlus);
        }

        res.put("topics",lists);

        return RestResponse.success(res);
    }

    @Override
    public RestResponse getMemberAdmin(String openid, String groupid,String date) {
        HashMap<String,Object> res = new HashMap<>();
        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息，请核对");

        QueryWrapper<CmtMember> qw = new QueryWrapper<>();
        qw.eq("group_id",groupid);
        ArrayList<CmtMember> lists = (ArrayList<CmtMember>) cmtMemberMapper.selectList(qw);
        ArrayList<MemberPlus2> finalres = new ArrayList<>();

        for (CmtMember member:lists){
            MemberPlus2 memberPlus2 = new MemberPlus2();
            memberPlus2.setInst(member.getInst());
            memberPlus2.setPost(member.getPost());
            memberPlus2.setName(member.getName());
            memberPlus2.setGroupId(member.getGroupId());
            memberPlus2.setMemberId(member.getMemberId());
            memberPlus2.setPostType(member.getPostType());
            memberPlus2.setOanum(member.getOanum());
            memberPlus2.setGroupName(member.getGroupName());

//            log.info("groupid》"+groupid);
            ArrayList<String> oanums = assessMapper.selectListByDate(Integer.valueOf(groupid),date,member.getMemberId());
            ArrayList<CmtMember> totalcmts = new ArrayList<>();
            for (int i = 0; i < oanums.size(); i++) {
                QueryWrapper<CmtMember> qw3 = new QueryWrapper<>();
                qw3.eq("oanum",oanums.get(i));
                CmtMember tmp = cmtMemberMapper.selectOne(qw3);
                totalcmts.add(tmp);
            }
            memberPlus2.setAmembers(totalcmts);
            memberPlus2.setCount(oanums.size());
            memberPlus2.setTotal(Math.max(lists.size() - 1, 0));

            finalres.add(memberPlus2);
        }

        res.put("members",finalres);
        return RestResponse.success(res);
    }


    @Override
    public RestResponse openAssGroup(String openid, String groupid, String date) {
        Group group = groupMapper.selectById(Integer.parseInt(groupid));
        if (group==null){
            log.info("没有该group");
            return RestResponse.failed("没有该group");
        }
        group.setStatus(date);
        int upflag = groupMapper.updateById(group);
        if (upflag>=1){
            log.info("更新group的status成功");
            QueryWrapper<GroupSubRecord> qw = new QueryWrapper<>();
            qw.eq("group_id",groupid).eq("submit_year",date);
            GroupSubRecord gsr = groupSubRecordMapper.selectOne(qw);
            if (gsr==null){
                log.info("添加一个group提交记录");
                GroupSubRecord tmp = new GroupSubRecord();
                tmp.setSubmitYear(date);
                tmp.setGroupId(Integer.parseInt(groupid));
                groupSubRecordMapper.insert(tmp);
            }else{
                log.info("已有记录，跳过该步骤");
            }
        }

        return RestResponse.success();
    }

    @Override
    public RestResponse closeAssGroup(String openid, String groupid, String date) {
        Group group = groupMapper.selectById(Integer.parseInt(groupid));
        if (group==null){
            log.info("没有该group");
            return RestResponse.failed("没有该group");
        }
        group.setStatus("");
        UpdateWrapper<Group> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("group_id", Integer.parseInt(groupid)); // 设置更新条件，这里以id为条件
        updateWrapper.set("status", null); // 设置name字段为null
        groupMapper.update(group,updateWrapper);
        log.info("更新group的status成功");
        return RestResponse.success();
    }

    @Override
    public RestResponse getAssGroup(String openid, String groupid, String date) {
        Group group = groupMapper.selectById(Integer.parseInt(groupid));
        if(group!=null&&group.getStatus()!=null){
            HashMap<String,Object> res = new HashMap<>();
            if(group.getStatus().equals(date)){
                res.put("code",true);
                log.info("已命中，有该记录");
            }else{
                res.put("code",false);
                res.put("date",group.getStatus());
                log.info("已命中，但date不一致");
            }
            return RestResponse.success(res);
        }
        log.info("未命中，无该记录");
        return RestResponse.failed();
    }

    public Workbook init_Workbook(ArrayList<String> sheets) {
        Workbook wb = new HSSFWorkbook();
        // fos = new FileOutputStream(fileOutputPath + filename);
        PropertyTemplate pt = new PropertyTemplate();
//        pt.drawBorders(new CellRangeAddress(frow,lrow,fcolum,lcolum),
//                BorderStyle.THIN, BorderExtent.ALL);
        for (String sheetName : sheets
        ) {
            Sheet sheet = wb.createSheet(sheetName);
            pt.applyBorders(sheet);
        }
        return wb;
    }

    public CellStyle setStyle(Workbook wb) {
        //设置单元格格式
        CellStyle cellStyle = wb.createCellStyle();
        //设置字体样式
        Font font = wb.createFont();
        //设置字体
        font.setFontHeightInPoints((short) 11);
        font.setFontName("宋体");
        cellStyle.setFont(font);
        //设置垂直对齐居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //设置水平对齐居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //设置自动换行
        cellStyle.setWrapText(true);
        return cellStyle;
    }


    @Override
    public RestResponse extractReport(String openid, String groupid, String date, HttpServletResponse response) {
        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息");
        if(staffInfo.getPriority()<2)
            return RestResponse.failed("无权限");

        log.info("开始报表导出");
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String nowTime = LocalDateTime.now().format(timeFormatter);
        ArrayList<String> sheets = new ArrayList<>();
        String sheetName = "报表结果";
        sheets.add(sheetName);
        String fileName = nowTime + SnowWorkId.generateId() + ".xlsx";

        try {
            Workbook wb = init_Workbook(sheets);
            CellStyle cellStyle = setStyle(wb);
            Sheet sheet = wb.getSheet(sheetName);
            //数据准备
            QueryWrapper<CmtMember> qw = new QueryWrapper<>();
            qw.eq("group_id",Integer.parseInt(groupid));
            ArrayList<CmtMember> cmts = (ArrayList<CmtMember>) cmtMemberMapper.selectList(qw); //总共有这么多个row
            ArrayList<MemberPlusWithReport> reports = new ArrayList<>();

            QueryWrapper<Topic> qw2 = new QueryWrapper<>();
            qw2.eq("group_id",groupid).eq("topic_date",date);
            ArrayList<Topic> topic_lists = (ArrayList<Topic>) topicMapper.selectList(qw2);
            DecimalFormat df = new DecimalFormat("0.00");

            Row row = sheet.createRow(0);
            int count = 0;
            //基本信息准备
            for (int i = 0; i < Constants.HEADER.size(); i++) {
                Cell cell = row.createCell(i);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(Constants.HEADER.get(i));
                count = i;
            }
            //题目信息准备

            for (int i = 0; i < topic_lists.size(); i++) {
                Cell cell = row.createCell(Constants.HEADER.size()+i);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(topic_lists.get(i).getTopicType()+"-"+topic_lists.get(i).getTopicDesc());
                count = Constants.HEADER.size()+i;
            }
            Cell cell = row.createCell(count+1);
            cell.setCellStyle(cellStyle);
            cell.setCellValue("有效填写人数");

            int j=1;
            int colum = 0;
            for (CmtMember member: cmts) {
                colum = 0;
                Row content = sheet.createRow(j);
                cell = content.createCell(colum++);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(j);  //序号
                j++;

                MemberPlusWithReport tmp = new MemberPlusWithReport();
                tmp.setName(member.getName());
                tmp.setInst(member.getInst());
                tmp.setPost(member.getPost());
                tmp.setGroupId(member.getGroupId());
                tmp.setOanum(member.getOanum());
                tmp.setGroupName(member.getGroupName());
                tmp.setPostType(member.getPostType());
                tmp.setMemberId(member.getMemberId());

                cell = content.createCell(colum++);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(member.getName());

                cell = content.createCell(colum++);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(member.getOanum());

                cell = content.createCell(colum++);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(member.getInst()); //部门

                cell = content.createCell(colum++);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(member.getPost()); //岗位

                cell = content.createCell(colum++);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(member.getPostType()); //干部类型

                ArrayList<TopicPlus2> topics = new ArrayList<>();
                int countPerson = 0;
                for (Topic single: topic_lists
                ) {
                    TopicPlus2 topicPlus2 = new TopicPlus2();
                    QueryWrapper<Assess> qw3 = new QueryWrapper<>();
                    qw3.eq("member_id",member.getMemberId())
                            .eq("group_id",Integer.parseInt(groupid))
                            .eq("topic_date",date).eq("topic_id",single.getTopicId());
                    ArrayList<Assess> assesses = (ArrayList<Assess>) assessMapper.selectList(qw3);
                    int good = 0;
                    int ok = 0;
                    int bad = 0;
                    for (int i = 0; i < assesses.size(); i++) {  //描述答案   good是1 ok是2 bad是3
                        if (assesses.get(i).getAnswerType()==1){
                            good+=1;
                        }else if(assesses.get(i).getAnswerType()==2){
                            ok+=1;
                        }else {
                            bad +=1;
                        }
                    }
                    HashMap<String,Object> scores = new HashMap<>();
                    scores.put("good",good);
                    scores.put("ok",ok);
                    scores.put("bad",bad);
                    topicPlus2.setTopicType(single.getTopicType());
                    topicPlus2.setTopicDate(single.getTopicDate());
                    topicPlus2.setTopicDesc(single.getTopicDesc());
                    topicPlus2.setTopicId(single.getTopicId());
                    topicPlus2.setAnswerDetail(scores);
                    topicPlus2.setGroupId(single.getGroupId());
                    topicPlus2.setGroupName(single.getGroupName());
                    topicPlus2.setCount(good+ok+bad);
                    topics.add(topicPlus2);
                    countPerson = Math.max(countPerson,good+ok+bad);
                    cell = content.createCell(colum++);
                    cell.setCellStyle(cellStyle);
                    double r;
                    try {
                        r = good/(double)(good+ok+bad);
                    }catch (ArithmeticException e){
                        r = 0.0;
                    }
                    if (Double.isNaN(r))
                        r = 0.0;
                    cell.setCellValue(df.format(r*100)+"%"); //问题好评比率
                }
                cell = content.createCell(colum);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(countPerson); //问题好评比率

                tmp.setTopics(topics);
                log.info("tmp>"+tmp);
                reports.add(tmp);
            }
            log.info("reports>"+reports);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            wb.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            // 设置响应参数
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            ServletOutputStream outputStream = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(outputStream);

            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            try {
                // fos.close();
                wb.close();
                bis.close();
                bos.close();
            } catch (Exception e) {
                log.error("文件流关闭失败");
                return RestResponse.failed("文件流关闭失败");
            }

        }catch (Exception e){
            throw new RuntimeException(e);
        }
        log.info("文件生成传输成功");
        return RestResponse.success("文件生成传输成功");
    }

    @Override
    public RestResponse deleteTopic(String openid, String topicid) {
        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息");
        if(staffInfo.getPriority()<2)
            return RestResponse.failed("无权限");

        int dflag = topicMapper.deleteById(Integer.parseInt(topicid));
        if (dflag>=1){
            return RestResponse.success("删除成功");
        }
        return RestResponse.failed("删除失败");    }

    @Override
    public RestResponse addTopic(String openid, String groupid, String date, String topicDesc, String topicType) {
        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息");
        if(staffInfo.getPriority()<2)
            return RestResponse.failed("无权限");

        Group group = groupMapper.selectById(Integer.parseInt(groupid));
        if (group!=null){
            Topic topic = new Topic();
            topic.setTopicType(topicType);
            topic.setTopicDate(date);
            topic.setTopicDesc(topicDesc);
            topic.setGroupId(Integer.parseInt(groupid));
            topic.setGroupName(group.getGroupName());

            if(topicMapper.insert(topic)>=1){
                return RestResponse.success("新增topic成功");
            };
        }
        return RestResponse.failed("新增topic失败");
    }

    @Override
    public RestResponse getTopic(String openid, String topicid) {
        HashMap<String,Object> res = new HashMap<>();

        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息");

        Topic topic = topicMapper.selectById(Integer.parseInt(topicid));
        res.put("topic",topic);
        return RestResponse.success(res);
    }

    @Override
    public RestResponse modifyTopic(String openid, String topicid,String topicDesc, String topicType) {
        HashMap<String,Object> res = new HashMap<>();

        StaffInfo staffInfo = getBaseMapper().selectById(openid);
        if (staffInfo==null)
            return RestResponse.failed("没找到员工信息");

        Topic topic = topicMapper.selectById(Integer.parseInt(topicid));
        if (topic!=null){
            topic.setTopicType(topicType);
            topic.setTopicDesc(topicDesc);
            if(topicMapper.updateById(topic)>=1){
                res.put("topic",topic);
                return RestResponse.success(res);
            }
        }
        return RestResponse.failed("更新topic失败");
    }
}
